package com.company.field;

import com.company.class1.Person;

import java.lang.reflect.Field;

public class TestFieldDemo {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {

        Class c = Person.class;
        // 得到所有公开的字段public
        Field[] f1 = c.getFields();
        for(Field f:f1)
        {
            System.out.println(f);
        }
        System.out.println("-------------------");
        //得到所有本类的字段
        Field[] f2 = c.getDeclaredFields();
        for(Field f:f2)
        {
            System.out.println(f);
        }

        System.out.println("-------------------");

        // 得到公开的某个属性
        Field f3 = c.getField("nickname");
        // 得到本身类的属性
        Field f4 = c.getDeclaredField("age");
        f4.setAccessible(true);

        Person p = new Person();
        f3.set(p, "老张");
        f4.set(p, 40);
        System.out.println(p);
    }
}
